package com.sfeir.server.dao;

import java.util.Collection;
import java.util.List;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.Transaction;

import com.sfeir.server.core.Indicator;

public class IndicatorDaoImpl implements IndicatorDao {
	private PersistenceManagerFactory pmf;

	public IndicatorDaoImpl(PersistenceManagerFactory pmf) {
		this.pmf = pmf;
	}

	/** Accessor for a PersistenceManager */
	protected PersistenceManager getPersistenceManager() {
		return pmf.getPersistenceManager();
	}


	@Override
	public Indicator getIndicator(String code) {
		Indicator result;
		PersistenceManager pm = getPersistenceManager();

		try {
			// load the child, "touch" it before closing the PersistenceManager
			// (LazyLoading)
			// see
			// http://code.google.com/intl/fr-FR/appengine/docs/java/datastore/relationships.html
			// see
			// http://code.google.com/p/googleappengine/issues/detail?id=2240
			pm.getFetchPlan().addGroup("graph");
			pm.getFetchPlan().addGroup("graph_curves");
			pm.getFetchPlan().setMaxFetchDepth(3);

			Indicator indicator = (Indicator) pm.getObjectById(Indicator.class, code);
			result = pm.detachCopy(indicator);

		} catch (JDOObjectNotFoundException e) {
			return null;
		} finally {
			pm.close();
		}

		return result;
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Indicator> getAllIndicators() {
		List<Indicator> indicators = null;
		PersistenceManager pm = getPersistenceManager();
		Transaction tx = pm.currentTransaction();

		Query q = pm.newQuery(Indicator.class);
		q.setOrdering("name ASC");

		try {
			tx.begin();

			Collection result = (Collection) q.execute();
			indicators = (List<Indicator>) pm.detachCopyAll(result);

			tx.commit();
		} finally {
			if (tx.isActive()) {
				tx.rollback();
			}
			q.closeAll();
			pm.close();
		}
		return indicators;
	}


	@Override
	public Indicator saveOrUpdate(Indicator newIndicator) {
		Indicator result;
		PersistenceManager pm = getPersistenceManager();
//		Transaction tx = pm.currentTransaction();
		try {
//			tx.begin();
			result = pm.makePersistent(newIndicator);
			result = pm.detachCopy(result);
//			tx.commit();
		} finally {
//			if (tx.isActive()) {
//				tx.rollback();
//			}
			pm.close();
		}
		return result;
	}
}
